package com.lingx.service;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.lingx.model.IContext;
import com.lingx.model.IPerformer;
import com.lingx.model.IValidator;
import com.lingx.model.impl.DefaultField;
import com.lingx.model.impl.DefaultMethod;
import com.lingx.utils.Utils;

@Component("lingxValidateService")
public class ValidateService {
	@Resource
	private ModelService modelService;
	public boolean validator(Map<String, Object> params, DefaultMethod method, IContext context, IPerformer performer,
			Map<String, Object> ret) {
		if (method.getValidation()) {
			for (DefaultField field : method.getFields().getList()) {
				if (field.getIsNotNull() && (!params.containsKey(field.getCode())||Utils.isNull(params.get(field.getCode()).toString()))) {
					ret.put("code", -1);
					ret.put("message", field.getName() + "不可为空!");
					return false;
				}
				
				if(Utils.isNotNull(field.getValidator())) {
					IValidator obj=this.modelService.getValidator(field.getValidator());
					if(obj!=null) {
						try {
							boolean b=obj.valid(params.get(field.getCode()), field.getValidatorParams(), params, field,context);
							if(!b) {
								ret.put("code", -1);
								ret.put("message",Utils.formatString(obj.getMessage(), field.getName()));
								return false;
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
		return true;
	}
}
